package com.meviewer.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;

public class FileUtil {
    public static boolean CreateFileParentDir(String filepath){
        //因为文件夹可能有多层，比如:  a/b/c/ff.txt  需要先创建a文件夹，然后b文件夹然后...
        String dir = filepath.substring(0,filepath.lastIndexOf("/"));
        try{
            File file=new File(dir);
            if(file.exists()){
                return true;
            }
            if(file.getParentFile().exists()){
                CreateDir(file.getParentFile().getAbsolutePath());
            }
            file.mkdirs();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean CreateDir(String filepath){
        //因为文件夹可能有多层，比如:  a/b/c/ff.txt  需要先创建a文件夹，然后b文件夹然后...
        String dir = filepath.substring(0,filepath.lastIndexOf("/"));
        try{
            File file=new File(dir);
            if(file.exists()){
                return true;
            }
            if(!file.getParentFile().exists()){
                CreateDir(file.getParentFile().getAbsolutePath());
            }
            file.mkdirs();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean WriteTxtFile(String strcontent,String strFilePath)
    {
        //每次写入时，都换行写
        String strContent=strcontent+"\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();;
        }
        return false;
    }

    //读取指定目录下的所有TXT文件的文件内容
    public static String ReadTxtFile(String path) {
        String content = "";
        File file = new File(path);
        try {
            InputStream instream = new FileInputStream(file);
            if (instream != null) {
                InputStreamReader inputreader
                        = new InputStreamReader(instream, StandardCharsets.UTF_8);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line = "";
                //分行读取
                while ((line = buffreader.readLine()) != null) {
                    content += line + "\n";
                }
                instream.close();//关闭输入流
            }
        } catch (java.io.FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    /* Get File Content With List<String> --------------------------------------------------------------------------- */

    public static List<String> read2List(String filePath) {
        return read2List(filePath, StandardCharsets.UTF_8);
    }

    public static List<String> read2List(String filePath, Charset charset) {
        return read2List(() -> {
            try {
                return bufferedReader(filePath, charset);
            } catch (IOException e) {
                return null;
            }
        });
    }

    public static List<String> read2List(InputStream is) {
        return read2List(is, StandardCharsets.UTF_8);
    }

    public static List<String> read2List(InputStream is, Charset charset) {
        return read2List(() -> bufferedReader(is, charset));
    }

    private static List<String> read2List(Supplier<BufferedReader> supplier) {
        List<String> contentList = new ArrayList<>();
        String temp;
        try (BufferedReader reader = supplier.get()) {
            while ((temp = reader.readLine()) != null) {
                contentList.add(temp);
            }
            return contentList;
        } catch (IOException e) {
            return contentList;
        }
    }

    /* Get File Content With String --------------------------------------------------------------------------------- */

    public static String read(String filePath) {
        return read(filePath, StandardCharsets.UTF_8);
    }

    public static String read(String filePath, Charset charset) {
        return read(() -> {
            try {
                return bufferedReader(filePath, charset);
            } catch (IOException e) {
                return null;
            }
        });
    }

    public static String read(InputStream is) {
        return read(is, StandardCharsets.UTF_8);
    }

    public static String read(InputStream is, Charset charset) {
        return read(() -> bufferedReader(is, charset));
    }

    private static String read(Supplier<BufferedReader> supplier) {
        StringBuilder content = new StringBuilder();
        String temp;
        try (BufferedReader reader = supplier.get()) {
            while ((temp = reader.readLine()) != null) {
                content.append(temp).append("\r\n");
            }
            return content.toString();
        } catch (IOException e) {
            return content.toString();
        }
    }

    /* Write File --------------------------------------------------------------------------------------------------- */

    public static void write(String filepath, String contents) {
        write(filepath, contents, StandardCharsets.UTF_8);
    }

    public static void write(String filepath, String contents, Charset charset) {
        try (BufferedWriter writer = bufferedWriter(filepath, charset)) {
            writer.write(contents +  "\r\n");
        } catch (IOException e) {
        }
    }

    public static void write(OutputStream os, String contents) {
        write(os, contents, StandardCharsets.UTF_8);
    }

    public static void write(OutputStream os, String contents, Charset charset) {
        try (BufferedWriter writer = bufferedWriter(os, charset)) {
            writer.write(contents +  "\r\n");
        } catch (IOException e) {
        }
    }

    public static void write(String filepath, List<String> contents) {
        write(filepath, contents, StandardCharsets.UTF_8);
    }

    public static void write(String filepath, List<String> contents, Charset charset) {
        try (BufferedWriter writer = bufferedWriter(filepath, charset)) {
            for (String content : contents) {
                writer.write(content +  "\r\n");
            }
        } catch (IOException e) {
        }
    }

    public static void write(OutputStream os, List<String> contents) {
        write(os, contents, StandardCharsets.UTF_8);
    }

    public static void write(OutputStream os, List<String> contents, Charset charset) {
        try (BufferedWriter writer = bufferedWriter(os, charset)) {
            for (String content: contents) {
                writer.write(content +  "\r\n");
            }
        } catch (IOException e) {
        }
    }

    /* BufferedReader ----------------------------------------------------------------------------------------------- */

    public static BufferedReader bufferedReader(String filename) throws IOException {
        return bufferedReader(filename, StandardCharsets.UTF_8);
    }

    public static BufferedReader bufferedReader(String filename, Charset charset) throws IOException {
        return bufferedReader(new File(filename), charset);
    }

    public static BufferedReader bufferedReader(File file) throws IOException {
        return bufferedReader(file, StandardCharsets.UTF_8);
    }

    public static BufferedReader bufferedReader(File file, Charset charset) throws IOException {
        return bufferedReader(new FileInputStream(file), charset);
    }

    public static BufferedReader bufferedReader(InputStream is) {
        return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    }

    public static BufferedReader bufferedReader(InputStream is, Charset charset) {
        return new BufferedReader(new InputStreamReader(is, charset));
    }

    /* BufferedWriter ----------------------------------------------------------------------------------------------- */

    public static BufferedWriter bufferedWriter(String filename) throws IOException {
        return bufferedWriter(filename, StandardCharsets.UTF_8);
    }

    public static BufferedWriter bufferedWriter(String filename, Charset charset) throws IOException {
        return bufferedWriter(new File(filename), charset);
    }

    public static BufferedWriter bufferedWriter(File file) throws IOException {
        return bufferedWriter(file, StandardCharsets.UTF_8);
    }

    public static BufferedWriter bufferedWriter(File file, Charset charset) throws IOException {
        return bufferedWriter(new FileOutputStream(file), charset);
    }

    public static BufferedWriter bufferedWriter(OutputStream os) {
        return new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
    }

    public static BufferedWriter bufferedWriter(OutputStream os, Charset charset) {
        return new BufferedWriter(new OutputStreamWriter(os, charset));
    }

    public static List<File> find(List<File> list, File file) {
        //判断file对象是否为空
        if(file == null){
            throw new NullPointerException("找不到路径啊！！！");
        }else if(file.isDirectory()) {
            //用数组来获取这个目录下的子文件夹
            File[] fs = file.listFiles();
            for(File f : fs) {
                //递归遍历所有子文件夹
                find(list,f);
            }
        }else if(file.isFile() && file.getName().endsWith("png")){
            list.add(file);
        }
        return list;


    }

    public static String getMarkImages(String path){

        //old version
        /*path = path.replace("file://","");
        List<File> list = new ArrayList<>();
        List<File> fileList = FileUtil.find(list, new File(path));
        List<String> res = new ArrayList<>();
        for (File file : fileList) {
            String s = ImageBase64Converter.convertFileToBase64(file);

            res.add(s);
        }
        return JSON.toJSONString(res);*/

        HashMap<String, String> res = new HashMap<>();


        path = path.replace("file://","");


       // System.out.println("------------------------");
       // System.out.println(path);
        List<File> list = new ArrayList<>();
        List<File> fileList = FileUtil.find(list, new File(path));
        //List<String> res = new ArrayList<>();
        for (File file : fileList) {
            String s = ImageBase64Converter.convertFileToBase64(file);
           // System.out.println("------------------------");
           // System.out.println(file.getName());
            res.put(file.getName(),s);
           // res.add(s);
        }
        //System.out.println("------------------------");
        //System.out.println(JSON.toJSONString(res));
        return JSON.toJSONString(res);



    }


}
